package com.hmdp.service.impl;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryShopById(Long id) {
        // 解决缓存穿透: 缓存null值
         Shop shop = cacheClient.queryWithPassThrough(
                 RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById,
                 RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        // 互斥锁解决缓存击穿
        // Shop shop = queryWithMutex(id);

        // 逻辑过期解决缓存击穿
//        Shop shop = cacheClient.queryWithLogicExpire(
//                RedisConstants.CACHE_SHOP_KEY, id, Shop.class,
//                this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        if (Objects.isNull(shop)){
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    /**
     * 解决商铺查询缓存击穿: 互斥锁
     * @param id 商铺id
     * @return 商铺信息
     */
    private Shop queryWithMutex(Long id) {
        Shop shop;
        // 1.Redis查询商铺缓存
        String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);
        if (StrUtil.isNotBlank(shopJson)){
            shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        // 命中是否为空值
        if (RedisConstants.CACHE_NULL_VALUE.equals(shopJson)){
            return null;
        }
        // 2.实现缓存重建
        // 2.1 获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        try {
            boolean isLock = tryLock(lockKey);
            // 2.2判断是否获取成功
            if (!isLock){
                // 2.3 获取锁失败，休眠并重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            // 2.4.1 获取锁成功，查询缓存
            shopJson = stringRedisTemplate.opsForValue().get(shopKey);
            if (StrUtil.isNotBlank(shopJson)){
                shop = JSONUtil.toBean(shopJson, Shop.class);
                return shop;
            }
            // 命中是否为空值
            if (RedisConstants.CACHE_NULL_VALUE.equals(shopJson)){
                return null;
            }
            // 2.4.2 获取锁成功，查询数据库
            shop = getById(id);
            // 模拟重建的延时
            Thread.sleep(200);
            if (ObjectUtil.isEmpty(shop)){
                // 将空值写入Redis
                stringRedisTemplate.opsForValue().set(shopKey, RedisConstants.CACHE_NULL_VALUE, RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            // 3.商铺数据写入Redis
            stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException();
        } finally {
            // 4.释放互斥锁
            unlock(lockKey);
        }
        // 5.返回商铺信息
        return shop;
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = new ThreadPoolExecutor(
            10,
            15,
            20, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(),
            ThreadFactoryBuilder.create().build(),
            new ThreadPoolExecutor.AbortPolicy());

    private Shop queryWithLogicExpire(Long id) {
        // 1.Redis查询商铺缓存
        String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);
        // 1.1 缓存未命中
        if (StrUtil.isBlank(shopJson)){
            // 直接返回null
            return null;
        }
        // 2.命中: json反序列化
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 3.判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())){
            // 3.1 未过期，直接返回店铺信息
            return shop;
        }
        // 3.2 已过期，需要缓存重建
        // 4.缓存重建
        // 4.1 获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        // 4.2 判断是否获取锁成功
        if (isLock){
            // 4.3 成功，开启独立线程，实现缓存重建
            // 4.3.1 再次查询缓存，命中直接返回
            shopJson = stringRedisTemplate.opsForValue().get(shopKey);
            if (StrUtil.isNotBlank(shopJson)){
                redisData = JSONUtil.toBean(shopJson, RedisData.class);
                shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
                expireTime = redisData.getExpireTime();
                // 3.判断是否过期
                if (expireTime.isAfter(LocalDateTime.now())){
                    // 3.1 未过期，直接返回店铺信息
                    return shop;
                }
            }
            // 4.3.2 未命中，缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    this.saveShop2Redis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放锁
                    unlock(lockKey);
                }
            });
        }
        return shop;
    }

    /**
     * 解决商铺查询缓存穿透: 缓存null值
     * @param id 商铺id
     * @return 商铺信息
     */
    private Shop queryWithPassThrough(Long id) {
        // 1.Redis查询商铺缓存
        String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);
        if (StrUtil.isNotBlank(shopJson)){
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        // 命中是否为空值
        if (RedisConstants.CACHE_NULL_VALUE.equals(shopJson)){
            return null;
        }
        // 2.缓存未命中: 查询数据库
        Shop shop = getById(id);
        if (ObjectUtil.isEmpty(shop)){
            // 将空值写入Redis
            stringRedisTemplate.opsForValue().set(shopKey, RedisConstants.CACHE_NULL_VALUE, RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 3.商铺数据写入Redis
        stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 4.返回商铺信息
        return shop;
    }

    /**
     * 获取互斥锁
     * @param key key
     * @return boolean
     */
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", RedisConstants.LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放互斥锁
     * @param key key
     */
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    public void saveShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
        // 1.查询店铺数据
        Shop shop = getById(id);
        Thread.sleep(200);
        // 2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 存入Redis
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateShop(Shop shop) {
        // 1.更新数据库
        updateById(shop);
        // 2.删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());

        return Result.ok();
    }

    /**
     * 根据店铺类型和地理坐标分页查询店铺信息
     *
     * @param typeId  店铺类型id
     * @param current 页码
     * @param x       x
     * @param y       y
     * @return R
     */
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1.判断是否需要坐标查询
        if (x == null || y == null) {
            // 不需要坐标查询，查询数据库
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        // 2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        // 3.查询Redis，按照距离排序、分页 结果:shopId、distance
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results =
                stringRedisTemplate.opsForGeo().radius(key,
                        new Circle(new Point(x, y), new Distance(5000, RedisGeoCommands.DistanceUnit.METERS)),
                RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().limit(end));
        if (null == results){
            return Result.ok(Collections.emptyList());
        }
        // 4.解析id
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from){
            // 沒有下一页,结束
            return Result.ok(Collections.emptyList());
        }
        // 4.1截取from~end
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            // 4.2获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 4.3获取店铺距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        // 5.根据id查询Shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query()
                .in("id", ids).last("ORDER BY FIELD(id," + idStr + ")")
                .list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 6.返回
        return Result.ok(shops);
    }
}
